package com.bracketbird.client.gui.club.tournament;

import com.bracketbird.client.*;
import com.bracketbird.client.event.*;
import com.bracketbird.client.gui.club.tournament.rtc.*;
import com.bracketbird.client.model.*;
import com.bracketbird.client.model.tournament.*;
import com.bracketbird.client.util.*;
import com.google.gwt.event.dom.client.*;
import com.bracketbird.clientcore.appcontrol.*;
import com.bracketbird.clientcore.gui.*;
import com.bracketbird.clientcore.style.*;
import com.bracketbird.clientcore.util.*;

import java.util.*;

/**
 *
 */
public class Participaters extends VerticalComponent {

    public String COL_ONE_LENGTH = "200px";
    public String COL_TWO_LENGTH = "250px";
    public String COL_THREE_LENGTH = "100px";
    public String COL_FOUR_LENGTH = "100%";
    private HorizontalComponent headerPanel;
    private HorizontalComponent newUser;
    private HyperlinkLabelComponent needHelp;


    public enum Focus {
        textbox,
        suggestbox,
    }

    private StringToMember stringToMembers = new StringToMember();

    private List<PlayingTeamComponent> playingTeams = new ArrayList<PlayingTeamComponent>();
    private VerticalComponent teamPanel;
    private HorizontalComponent controlPanel;
    private HorizontalComponent addTeam;
    private ParticipatersFocusManager focusManager;
    private SimplePanelComponent teamTableHolder = new SimplePanelComponent();


    private TournamentListener<TournamentTeamEvent> teamListener = new TournamentListener<TournamentTeamEvent>() {
        public void onChange(TournamentTeamEvent event) {
            if (event.getAction() == TournamentTeamEvent.Action.create) {
                addTeam(event.getTeam());
                updateTeamNames();
                ApplicationController.scrollDown();
            }
            else if (event.getAction() == TournamentTeamEvent.Action.delete) {
                delete(event.getTeam());
                updateTeamNames();
            }
        }
    };


    public Participaters(Collection<Member> members) {
        super();

        RTC.getInstance().getTournament().addTeamsListener(teamListener);
        focusManager = new ParticipatersFocusManager(this);
        stringToMembers.add(members);

        EventManager.eventBus.addHandler(MemberCreatedEvent.TYPE,
                new MembersCreatedHandler() {
                    public void onChange(MemberCreatedEvent event) {
                        stringToMembers.add(event.getMember());
                        for (PlayingTeamComponent playingTeam : playingTeams) {
                            playingTeam.updateMembersSuggestList();
                        }
                    }
                });


        add(getHeaderPanel(), new TextLayout(0, 0, 10, 0, null, "100%").borderBottom(1).borderColor(P.COLOR_C1));

        teamTableHolder.add(getTeamPanel(), new TextLayout(null, "100%"));
        add(teamTableHolder, new TextLayout(null, "100%"));
        add(getControlPanel(), new TextLayout(20, 0, 0, 0, null, "100%"));
    }


    private void updateTeamNames() {
        int i = 1;
        for (PlayingTeamComponent pt : playingTeams) {
            if (!PlayingTeam.isTeamNameValid(pt.getPlayingTeam().getTeamName())) {
                pt.getTeamName().setText("Team " + i);
            }
            i++;
        }
    }


    public HorizontalComponent getHeaderPanel() {
        if (headerPanel == null) {
            headerPanel = new HorizontalComponent();
            addHeader(headerPanel, "Team name", COL_ONE_LENGTH);
            addHeader(headerPanel, "Players", COL_TWO_LENGTH);
            addHeader(headerPanel, "Seeding", COL_THREE_LENGTH);
            addHeader(headerPanel, "Comments", COL_FOUR_LENGTH);

        }
        return headerPanel;
    }

    public void addHeader(HorizontalComponent hc, String header, String size) {
        HorizontalComponent hcTemp = new HorizontalComponent();
        hcTemp.add(new LabelComponent(header), new TextLayout(null, size, Horizontal.LEFT).sizeSmall().bold().italic().colorBaseDark());
        hc.add(hcTemp, new TextLayout(null, size));
    }


    public HorizontalComponent getControlPanel() {
        if (controlPanel == null) {
            controlPanel = new HorizontalComponent();
            //controlPanel.add(getAllowNonMembers(), new TextLayout(0, 15, 0, 10, Vertical.MIDDLE).sizeSmall().colorBaseDark().alignCenter().noWrap());
            //controlPanel.add(getNewUser(), new TextLayout(Vertical.MIDDLE));
            //controlPanel.add(getNeedHelp(), new TextLayout(0,0,0,10,Vertical.MIDDLE).sizeSmall().colorBaseDark().backgroundYellow().padding(4).noWrap().underline());

            controlPanel.add(new SimplePanelComponent(), new TextLayout(null, "100%"));
        }
        return controlPanel;
    }


    public HorizontalComponent getNewUser() {
        if (newUser == null) {
            newUser = new HorizontalComponent();
            String title = "Create a new member of " + UserManager.getInstance().getClub().getName();
            ImageComponent img = new ImageComponent("newUser.png");
            img.setTitle(title);
            img.getImage().addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    createUser();
                }
            });
            img.getImage().addMouseOverHandler(MouseOver.POINTER);
            newUser.add(img, new TextLayout(0, 0, 0, 0, Vertical.MIDDLE));

            LabelComponent l = new LabelComponent("Create member");
            l.setTitle(title);
            l.getLabel().addMouseOverHandler(MouseOver.POINTER);
            l.getLabel().addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                    createUser();

                }

            });
            newUser.add(l, new TextLayout(0, 0, 0, 4).colorBaseDark().sizeSmall().noWrap());
        }
        return newUser;
    }


    private void createUser() {
//        PopUpDataPageController.showCreateMember();

    }





    public VerticalComponent getTeamPanel() {
        if (teamPanel == null) {
            teamPanel = new VerticalComponent();
        }
        return teamPanel;
    }




    private void addTeam(PlayingTeam team) {
        HorizontalFocusManager hf = new HorizontalFocusManager();
        focusManager.addChild(hf);
        PlayingTeamComponent tc = new PlayingTeamComponent(team, hf, this, stringToMembers, true);
        playingTeams.add(tc);
        getTeamPanel().add(tc, new TextLayout(2, 0, 2, 0, null, "100%").borderBottom(1).borderColor(P.COLOR_C1));
    }

    public void setFocusOnLastComponent() {
        //TODO - focus control should be moved to RTC
        if (!playingTeams.isEmpty()) {
            PlayingTeamComponent pc = playingTeams.get(playingTeams.size() - 1);
            pc.getTeamName().setFocus(true);
            //navigate to the rigth.
            ((HorizontalFocusManager) pc.getFocusManager()).right(new FocusKeyDownEvent(pc.getTeamName(), 39));

        }


    }


    public void delete(PlayingTeam team) {
        PlayingTeamComponent playingTeamComponent = getPlayingTeamComponent(team);
        focusManager.remove(playingTeamComponent.getFocusManager());
        playingTeams.remove(playingTeamComponent);
        playingTeamComponent.removeFromParent();
    }

    public boolean lastTeamHasPlayers() {
        return playingTeams.get(playingTeams.size() - 1).getPlayingTeam().isEmpty();
    }

    private PlayingTeamComponent getPlayingTeamComponent(PlayingTeam team) {
        for (PlayingTeamComponent comp : playingTeams) {
            if (comp.getPlayingTeam().equals(team)) {
                return comp;
            }
        }
        throw new SystemException("Unable to find playingTeamComponent when deleting team");
    }


    public void setFocus(boolean focus) {
        if (focus) {
            focusManager.setFocus();
        }
        else {

        }

    }
}
